function findValue(li,id) {
	var tmp = "#id_" + id;
	var tmp2 = "#id_autocomplete_" +id;
	if( li == null) 
		$(tmp).val('');
	else {
		try {
			$(tmp).val(li.extra[0]);
		} catch(err) {
			$(tmp).val('');
		}
	}
		
}

function selectItem(li, id) {
	var tmp = "#id_" + id;
	var tmp2 = "#id_autocomplete_" +id;
	findValue(li, id);
	$(tmp).trigger('change');
	$(':input[tabindex=' + (parseInt($(tmp2).attr('tabindex'))+1) + ']').focus();
}

function formatItem(row) {
	return row[0] + " (id: " + row[1] + ")";
}

function aschange(id){
	var tmp = "#id_" + id;
	var tmp2 = "#id_autocomplete_" +id;
	var oSuggest = $(tmp2)[0].autocompleter;
	findValue(oSuggest,id);
	$(tmp).trigger('change');
	if  ($(tmp).val()== '') {
		$(tmp2).val('');
	}
}


function doajax(id,cls){
	var tmp = "#id_" + id;
	var tmp2 = "#id_autocomplete_" +id;
	var add_tmp ="#add_id_" + id;
	if ($(tmp).val()!='') {
		var the_id = $(tmp).val()	
				$.getJSON("/autocomplete_id/"+cls+"/" +the_id+ "/",{}, function(json){
			$(tmp2).val(json['result']);
				});
	}else{
		var t = $(tmp2).val();
		if (t != '') {
			if (confirm('Registro no encontrado. ¿Desea agregarlo ahora?')) {
				$(add_tmp).click();
				$(tmp2).val('');
			} else {
				$(tmp2).val('');
				$(tmp).focus();
			}
		}
	}
}
				
function autocomplete_field (id, fields, cls)
{				
	$("#id_autocomplete_"+id).change(function() {aschange(id)});
	$("#id_"+id).change(function() {doajax(id,cls)});
	$("#id_autocomplete_"+id).autocomplete('/autocomplete/'+cls+'/'+fields+'/',{
		delay:10,
		minChars:1,
		mustMatch: 0,
		matchSubset:10,
		matchContains:1,
		matchCase: 0,
		maxItemsToShow: 50,
		selectFirst: 1,
		cacheLength:1,
		onFindValue:findValue,
		onItemSelect:selectItem,
		formatItem: formatItem,
		autoFill:false,
		id: id})
}				
